import { z } from 'zod';
import { router } from '../trpc';
import { protectedProcedure } from '../middleware';
import { UserService } from '../../services/userService';
import { createSuccessResponse, createErrorResponse } from '../../utils/response';

// 输入验证schemas
const updateProfileSchema = z.object({
  username: z.string().min(3, 'Username must be at least 3 characters').optional(),
  avatar: z.string().url('Invalid avatar URL').optional(),
});

const getRechargeRecordsSchema = z.object({
  page: z.number().int().positive().default(1),
  limit: z.number().int().positive().max(100).default(20),
});

export const userRouter = router({
  /**
   * 获取当前用户详细信息
   */
  getProfile: protectedProcedure
    .query(async ({ ctx }) => {
      try {
        const user = await UserService.getUserById(ctx.user.userId);
        if (!user) {
          return createErrorResponse('User not found', 'USER_NOT_FOUND');
        }

        const { password: _, ...userWithoutPassword } = user;
        return createSuccessResponse(userWithoutPassword, 'Profile retrieved successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to get profile',
          'USER_ERROR'
        );
      }
    }),

  /**
   * 更新用户资料
   */
  updateProfile: protectedProcedure
    .input(updateProfileSchema)
    .mutation(async ({ input, ctx }) => {
      try {
        const updatedUser = await UserService.updateUser(ctx.user.userId, input);
        const { password: _, ...userWithoutPassword } = updatedUser;
        return createSuccessResponse(userWithoutPassword, 'Profile updated successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to update profile',
          'USER_ERROR'
        );
      }
    }),

  /**
   * 获取用户充值记录
   */
  getRechargeRecords: protectedProcedure
    .input(getRechargeRecordsSchema)
    .query(async ({ input, ctx }) => {
      try {
        const result = await UserService.getUserRechargeRecords(
          ctx.user.userId,
          input.page,
          input.limit
        );
        return createSuccessResponse(result, 'Recharge records retrieved successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to get recharge records',
          'USER_ERROR'
        );
      }
    }),

  /**
   * 获取用户统计信息
   */
  getStats: protectedProcedure
    .query(async ({ ctx }) => {
      try {
        const user = await UserService.getUserById(ctx.user.userId);
        if (!user) {
          return createErrorResponse('User not found', 'USER_NOT_FOUND');
        }

        const rechargeRecords = await UserService.getUserRechargeRecords(ctx.user.userId, 1, 1);
        
        return createSuccessResponse(
          {
            userId: user.id,
            username: user.username,
            email: user.email,
            role: user.role,
            isActive: user.isActive,
            lastLoginAt: user.lastLoginAt,
            createdAt: user.createdAt,
            totalRechargeRecords: rechargeRecords.total,
          },
          'User stats retrieved successfully'
        );
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to get user stats',
          'USER_ERROR'
        );
      }
    }),
});
